//
// Created by augtons on 2022/1/7.
//

#include "my_wifi.h"
#include "my_udp.h"

void __attribute__((weak)) onWifiStarted(){
    esp_wifi_connect();
}

void __attribute__((weak)) onWifiStoped(){
//    esp_wifi_connect();
}

void __attribute__((weak)) onWifiConnected(wifi_event_sta_connected_t *data){
    xEventGroupSetBits(wifiEventGroup, WIFI_CONNECTED_BIT);
}

void __attribute__((weak)) onWifiDisConnected(wifi_event_sta_disconnected_t *data){
    xEventGroupClearBits(wifiEventGroup, WIFI_CONNECTED_BIT);
}

void __attribute__((weak)) onGotIP(ip_event_got_ip_t *data){
    xEventGroupSetBits(wifiEventGroup, IP_GOT_BIT);

    gpio_set_level(GPIO_NUM_2, 1);

    computer_udp_manager.create();
    phone_udp_manager.create();
}

void __attribute__((weak)) onLostIP(){
    xEventGroupClearBits(wifiEventGroup, IP_GOT_BIT);

    gpio_set_level(GPIO_NUM_2, 0);

    computer_udp_manager.destroy();
    phone_udp_manager.destroy();
}


void wifiEventHandler(void* arg,
                    esp_event_base_t event_base,
                    int32_t event_id,
                    void* event_data)
{
    switch (event_id){
        case WIFI_EVENT_STA_START:{
            onWifiStarted();
            break;
        }
        case WIFI_EVENT_STA_DISCONNECTED:{
            onWifiDisConnected(event_data);
            break;
        }
        case WIFI_EVENT_STA_CONNECTED:{
            onWifiConnected(event_data);
            break;
        }
        case WIFI_EVENT_STA_STOP:{
            onWifiStoped();
            break;
        }
    }
}

void ipEventHandler(void* arg,
                      esp_event_base_t event_base,
                      int32_t event_id,
                      void* event_data)
{
    switch (event_id) {
        case IP_EVENT_STA_GOT_IP:{
            onGotIP(event_data);
            break;
        }
        case IP_EVENT_STA_LOST_IP:{
            onLostIP();
            break;
        }
    }
}


void initNvs(){
    esp_err_t err = nvs_flash_init();
    if (err == ESP_ERR_NVS_NO_FREE_PAGES || err == ESP_ERR_NVS_INVALID_STATE) {
        nvs_flash_erase();
        ESP_ERROR_CHECK(nvs_flash_init());
    }
}

void initWifi(){
    esp_netif_init();
    initUDPSockets();
    esp_event_loop_create_default();
    wifiSTADefaultNetif = esp_netif_create_default_wifi_sta();
    wifi_init_config_t wifiInitConfig = WIFI_INIT_CONFIG_DEFAULT();
    esp_wifi_init(&wifiInitConfig);
    wifi_config_t wifiConfig = {
        .sta = {
            .ssid = "改成你的WiFissid",
            .password = "WiFi密码",
        }
    };
    esp_wifi_set_config(WIFI_IF_STA, &wifiConfig);
    esp_event_handler_instance_register(WIFI_EVENT, ESP_EVENT_ANY_ID, wifiEventHandler, NULL, &wifiEventHandlerInstance);
    esp_event_handler_instance_register(IP_EVENT, ESP_EVENT_ANY_ID, ipEventHandler, NULL, &ipEventHandlerInstance);
    esp_wifi_set_mode(WIFI_MODE_STA);
    esp_wifi_start();
}